package leetcode;

import java.util.Deque;
import java.util.LinkedList;

public class Code007_MaxSlidingWindow {

    public static int[] maxSlidingWindow(int[] nums, int k) {
        if (k > nums.length || nums == null || k < 1) {
            return null;
        }
        Deque<Integer> deque = new LinkedList<>();
        int[] res = new int[nums.length - k + 1];
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            while (!deque.isEmpty() && nums[i] > nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.addLast(i);
            if (i - deque.peekFirst() == k) {
                deque.pollFirst();
            }
            if (i >= k - 1) {
                res[index] = nums[deque.peekFirst()];
                index++;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {9,11};
        int[] res = maxSlidingWindow(nums, 2);
        for(int cur : res){
            System.out.print( cur +", ");
        }
    }
}
